package com.youshang.config;

import com.youshang.kafkalearning.model.UserModel;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author youshang
 * @date 2021/01/12 10:26
 **/
public class TestAvroSpecific {

    public static void main(String[] args) throws IOException {
        //方法1：使用new方法
        UserModel s1 = new UserModel(123,"10",18);

        System.out.println(s1);

        //方法2：使用set方法
        UserModel s2 = new UserModel();
        s2.setName("David");
        s2.setId(1234);
        s2.setAge(15);

        System.out.println(s2);

        //方法3：使用build 方法
        UserModel s3 = UserModel.newBuilder().setName("Lucy").setAge(20).setId(12345).build();


        //加入list
        List<UserModel> studentList = new ArrayList<>();
        studentList.add(s1);
        studentList.add(s2);
        studentList.add(s3);
        //写入文件中 序列化文件
        serializeAvroToFile(studentList,"myFile.txt");
        //读取文件 反序列化文件
        deserializeAvroFromFile("myFile.txt");

    }


    //使用avro协议序列化对象到文件中
    private static void serializeAvroToFile(List<UserModel> userModelList,String fileName) throws IOException {

        DatumWriter<UserModel> datumWriter = new SpecificDatumWriter<UserModel>(UserModel.class);
        DataFileWriter<UserModel> dataFileWriter = new DataFileWriter<UserModel>(datumWriter);
        dataFileWriter.create(userModelList.get(0).getSchema(), new File(fileName));
        for (UserModel student: userModelList) {
            dataFileWriter.append(student);
        }
        dataFileWriter.close();
    }


    //使用avro协议反序列化对象到内存并且打印
    private static void deserializeAvroFromFile(String fileName) throws IOException {
        File file = new File(fileName);
        DatumReader<UserModel> datumReader = new SpecificDatumReader<UserModel>(UserModel.class);
        DataFileReader<UserModel> dataFileReader = new DataFileReader<UserModel>(file, datumReader);
        UserModel userModel = null;
        System.out.println("----------------deserializeAvroFromFile-------------------");
        while (dataFileReader.hasNext()) {
            userModel = dataFileReader.next(userModel);
            System.out.println("deserializeAvroFromFile:"+userModel);
        }
    }
}
